/* eslint-disable */
(async () => {
  // 不需要显示的以zbj域名
  const blacklist = [
    'work.cs.zbj.com'
  ];
  const taxTypeObjectBase = {
    balance: {
      name: '资产负债表',
      type: 'balance'
    },
    profit: {
      name: '利润表',
      type: 'profit'
    },
    cash: {
      name: '现金流量表',
      type: 'cash'
    },
    sds: {
      name: '所得税',
      type: 'sds'
    },
    zzs: {
      name: '增值税',
      type: 'zzs'
    }
  };
  const hsqjTypeObject = {
    hsqj2007: {
      name: '汇算清缴',
      type: 'hsqj',
      ins: '2007'
    }
  };
  const outPutCity = ['上海', '河南', '辽宁', '新疆'];

  let urls = await getCulPage();

  let baseInfo = {};


  if (blacklist.find(item => window.location.href.includes(item))) {
    return false;
  }
  if (!urls || (urls.inject && urls.inject === 'saas.js')) {
    return false;
  } else {
    if ($('body').length) {
      loadingPage();
    } else {
      window.location.href = document.getElementsByTagName('frame')[1].src;
    }
  }

  function loadingPage() {
    // saas 跳转获得填报信息
    chrome.runtime.sendMessage(
      {
        event: 'getBaseInfo'
      },
      data => {
        if (!data.data.companyInfo || !data.data.companyInfo.accountBookName) {
          return true;
        }
        baseInfo = data.data;
        addPopup(data.data);
        // 添加popup 信息
        addBaseInfo(data.data); // 版本号、账套名、会计制度、纳税人类型、
        dealSystem(data.data); // 会计制度
        dealCycle(data.data); // 申报周期
        dealType(data.data); // 报表类型
        dealMethods(data.data); // 申报方式
      }
    );

    // 新版本
    chrome.runtime.onConnect.addListener(function (port) {
      if (port.name === 'toInject') {
        port.onMessage.addListener(data => {
          if (data.event === 'getNewVersionInfo') {
            showUpdate(data.data);
          }
        })
      }
    })
  }

  function compareVersion(versionA, versionB) {
    let arrA = versionA.split(".");
    let arrB = versionB.split(".");
    let a = parseFloat(arrA[0]) * 1000 + parseFloat(arrA[1]) + parseFloat(arrA[2]) * 0.001;
    let b = parseFloat(arrB[0]) * 1000 + parseFloat(arrB[1]) + parseFloat(arrB[2]) * 0.001;
    return a > b;
  }

  const showUpdate = res => {
    let cdnVersion = res.version;
    let manifest = chrome.runtime.getManifest();
    let domUpdate = $('#yijianbaoshuiNewVersionNumber');
    if (compareVersion(cdnVersion, manifest.version)) {
      domUpdate.css('display', 'block');
      domUpdate.text('更新版本' + cdnVersion);
    } else {
      domUpdate.css('display', 'none');
    }
  };

  // 自动同步账期和类型
  window.addEventListener(
    'message',
    function ({ data }) {
      // 不监听自己给自己发的信息
      if (data.sender !== 'content-script') {
        if (data.event === 'setPeriodAndType') {
          webData = data.data;
          dealCycle({
            webData
          });
          changeType({
            webData
          }, baseInfo.companyInfo);
        }
      }
    },
    false
  );

  function addBaseInfo({ companyInfo = {}, webData, taxConfig = [] }) {
    $('#accountBookName').text(companyInfo.accountBookName || '');
    $('#taxpayerName').text(companyInfo.taxpayerName || '');
    let manifest = chrome.runtime.getManifest();
    $('#yijianbaoshuiVersionNumber').text(manifest.version);
    if (!(taxConfig[0] && taxConfig[0].isSupportSyncDeclareType)) {
      $('#syncDeclarationTypes').css('display', 'none');
      $('#syncDeclarationList').css('display', 'none');
    }
  }

  // 申报方式
  const dealMethods = ({ taxConfig = [] }) => {
    const currentCityTaxConfig = taxConfig[0] || {};
    if (currentCityTaxConfig.isSupportTaxNationType) {
      $('#dealMethods').text('导出申报');
      $('#oneKeyTaxReport').text('导出报税');
      return false;
    }
    $('#dealMethods').text('一键申报');
    $('#oneKeyTaxReport').text('一键报税');
  };
  // 会计制度
  const dealSystem = ({ taxConfig = [], companyInfo = {} }) => {
    const currentCityTaxConfig = taxConfig[0] || {};
    if (currentCityTaxConfig.isSupportTaxNationType) {
      let institutionName;
      if (companyInfo && companyInfo.institutionName.includes('小企业会计准则')) {
        institutionName = `<option selected value="2013">小企业会计准则</option>
      <option value="2007">企业会计准则</option>`;
      } else {
        institutionName = `<option value="2013">小企业会计准则</option>
      <option selected value="2007">企业会计准则</option>`;
      }

      $('#institutionName').html(
        `<select id="taxRepotIns" value="2007" class="report-select">${institutionName}</select>
        `
      );
      return false;
    }
    $('#institutionName').html(companyInfo.institutionName || '');
  };

  // 设置申报周期
  const dealCycle = ({ companyInfo = {}, webData = {} }, type = '') => {
    if (type) {
      // console.log(baseInfo);
      let year = dayjs().year();
      let curYear = year - 1;
      $('#period-start').val(`${curYear}-01`);
      $('#period-end').val(`${curYear}-12`);
      return;
    }
    let financeReportType = companyInfo.financeReportType || 'NO';
    let curYear = companyInfo.curYear;
    let end = Number.parseInt(companyInfo.curPeriod || 0);
    let start = null;
    let time = {};

    if (webData.startTime && webData.endTime) {
      // 优先以国税局中获取时间为准
      time = {
        start: webData.startTime,
        end: webData.endTime
      };
    } else if (financeReportType === 'QUARTER' || financeReportType === "NO") {
      if ([1, 2, 3].includes(parseInt(end))) start = 1;
      if ([4, 5, 6].includes(parseInt(end))) start = 4;
      if ([7, 8, 9,].includes(parseInt(end))) start = 7;
      if ([10, 11, 12].includes(parseInt(end))) start = 10;
      // end = start + 2;
      // curYear = start > 0 ? curYear : curYear - 1;
      time = {
        start: curYear + '-' + (start >= 10 ? start : '0' + start),
        end: curYear + '-' + (end >= 10 ? end : '0' + end)
      };
    } else if (financeReportType === 'MONTH') {
      start = end;
      time = {
        start: curYear + '-' + (start >= 10 ? start : '0' + start),
        end: curYear + '-' + (end >= 10 ? end : '0' + end)
      };
    }
    $('#period-start').val(time.start);
    $('#period-end').val(time.end);
  };

  // 报表类型
  function dealType({ taxConfig = [], companyInfo = {}, webData = {} }) {
    let taxTypeObject = isOpenHSQJ()
      ? Object.assign({}, taxTypeObjectBase, hsqjTypeObject)
      : taxTypeObjectBase;
    const currentCityTaxConfig = taxConfig[0] || {};
    const supportTaxType = currentCityTaxConfig.supportTaxType || [];

    if (outPutCity.includes(currentCityTaxConfig.name)) {
      return false;
    }
    addOptionsHtml(taxTypeObject, supportTaxType, companyInfo);
  }
  function changeTypeAddItem(type, companyInfo = {}) {
    // isRearrange 是否往来重分类 0:否 1:是
    // isCashRearrange 是否现金流量表重分类 0:否 1:是
    // let { isRearrange = 0, isRearrangeNew = 0} = companyInfo;
    let { isRearrange = 1, isCashRearrange } = companyInfo;
    const yijianbaoshuiZero = $('#yijianbaoshuiZero');
    const yijianbaoshuiClass = $('#yijianbaoshuiClass');
    if (type === 'balance') {
      yijianbaoshuiZero.hide();
      yijianbaoshuiClass.show();
      let yijianbaoshuiClassBtn = yijianbaoshuiClass.find('.J-yijianbaoshui-class')
      if (!isRearrange) {
        yijianbaoshuiClassBtn.removeClass('yijianbaoshui-radio-icon-select');
      } else {
        yijianbaoshuiClassBtn.addClass('yijianbaoshui-radio-icon-select');
      }

    } else if (type === 'cash') {
      $('#yijianbaoshuiClass').show();
      $('#yijianbaoshuiZero').show();
      if (!isCashRearrange) {
        $('.J-yijianbaoshui-class').removeClass('yijianbaoshui-radio-icon-select');
      } else {
        $('.J-yijianbaoshui-class').addClass('yijianbaoshui-radio-icon-select');
      }
    } else {
      $('#yijianbaoshuiClass').hide();
      $('#yijianbaoshuiZero').hide();
    }

    if (type === "hsqj") {
      dealCycle(baseInfo, true);
    }

  }
  const changeType = ({ webData }, companyInfo) => {
    let taxTypeObject = isOpenHSQJ()
      ? Object.assign({}, taxTypeObjectBase, hsqjTypeObject)
      : taxTypeObjectBase;
    let selectedOption = taxTypeObject[webData.type];
    if (selectedOption) {
      $('#tax-type > select').val(selectedOption.name);
    }
    changeTypeAddItem(webData.type, companyInfo);
  };
  // 添加报表选项选项
  const addOptionsHtml = (taxTypeObject, supportTaxType, companyInfo) => {
    let taxTypeOptionsHtml = '';
    let newTaxTypeObject = supportTaxType.reduce(
      (result, item) =>
        Object.assign(result, {
          [item]: taxTypeObject[item]
        }),
      {}
    );

    Object.keys(newTaxTypeObject).forEach(key => {
      // 只渲染支持的选项
      if (newTaxTypeObject[key]) {
        let item = newTaxTypeObject[key] || {};
        if (item.type === 'balance') {
          taxTypeOptionsHtml += `<option data-type="${item.type}" ${item.ins ? 'data-ins=' + item.ins : ''
            }>${item.name}</option>`;
        } else {
          taxTypeOptionsHtml += `<option data-type="${item.type}" ${item.ins ? 'data-ins=' + item.ins : ''
            }>${item.name}</option>`;
        }
      }
    });
    $('.yijianbaoshui-tax-type').removeClass('yijianbaoshui-tax-type');
    $('#tax-type').html(
      '<select id="taxTypeSelect" class="report-select">' + taxTypeOptionsHtml + '</select>'
    );
    setTimeout(() => {
      $('#yijianbanshuiSelect').show();
      changeTypeAddItem('balance', companyInfo);
      $('#taxTypeSelect').change(function () {
        let type = $('#tax-type > select').find('option:selected')[0].dataset.type;
        changeTypeAddItem(type, companyInfo);
      })
    }, 1000)

  };


  // 是否开启汇算清缴
  const isOpenHSQJ = () => {
    const currentMonth = new Date().getMonth() + 1;
    return currentMonth >= 3 && currentMonth < 6; // 逻辑暂定为 4 5月份 开启汇算清缴申报功能;
  };


  // 是否支持年报
  const isSupportCwbbYears = (companyInfo, postData) => {
    let { startTime, endTime, type } = postData;

    // 是否为年报
    let period = parseInt(endTime.split('-')[1]) - parseInt(startTime.split('-')[1]);
    if (period !== 11) return {
      isSupportLastYears: true,
      isSupportLastYearsBefore: true,
    };

    // 是否支持年报
    var date = new Date;
    var current = date.getFullYear()
    let { startDate = current } = companyInfo;
    return {
      isSupportLastYears: current - parseInt(startDate.split('-')[0]) >= 1,
      isSupportLastYearsBefore: current - parseInt(startDate.split('-')[0]) >= 2,
    };
  }

  // 基础html
  function addPopup() {
    let btn = $(`<div id="yiJianBaoShuiBtn" class="yijianbaoshui-btn">
    <span class="yijiaobaoshui-btn-text">报税</span>
  <img crossOrigin="Anonymous" src="" alt="">
</div>`);
    let main = $(`<div id="yiJianBaoShuiPopup" class="yijianbaoshui">
        <div class="yijianbaoshui-main">
          <div class="yijianbaoshui-item">
            <span class="yijianbaoshui-item_one">版本号： </span>
            <span id="yijianbaoshuiVersionNumber"></span>
            <span class="yijianbanshui-new-version-number" id="yijianbaoshuiNewVersionNumber"></span>
          </div>
          <div class="yijianbaoshui-item">
            <span class="yijianbaoshui-item_one" >账套名： </span>
            <span id="accountBookName"></span>
          </div>
          <div class="yijianbaoshui-item">
            <span class="yijianbaoshui-item_one">会计制度：</span>
            <span id="institutionName"></span>
          </div>
          <div class="yijianbaoshui-item">
            <span class="yijianbaoshui-item_one">纳税人类型： </span>
            <span id="taxpayerName"></span>
          </div>
          <div class="yijianbaoshui-item">
            <span class="yijianbaoshui-item_one">申报方式： </span>
            <span class="yijianbaoshui-item_two" id="dealMethods">
              一键申报
            </span>
          </div>
          <div class="yijianbaoshui-item">
            <span class="yijianbaoshui-item_one">申报周期： </span>
            <span class="yijianbaoshui-item-time">
              <input class="input-period-time" type="month" id="period-start" value="2019年1月">
              <span>至</span>
              <input class="input-period-time" type="month" id="period-end" value="2019年1月">
            </span>
          </div>
          <div class="yijianbaoshui-item yijianbaoshui-tax-type">
            <span class="yijianbaoshui-item_one">报表类型： </span>
            <div class="yijianbaoshui-item_two" id="tax-type">
              <ul class="tax-type-ul">
              <li class="tax-type-li"> <span></span> 资产负债表</li>
              <li class="tax-type-li"> <span></span> 利润表</li>
              <li class="tax-type-li"> <span></span> 现金流量</li>
            </ul>
            </div>
          </div>
          <div class="yijianbaoshui-item"  id="yijianbanshuiSelect">
            <div>
              <div id="yijianbaoshuiClass">重分类<div class="yijianbaoshui-radio-icon yijianbaoshui-radio-icon-select J-yijianbaoshui-class"></div></div>
              <div style="height: 5px"></div>
              <div id="yijianbaoshuiZero">零申报<div class="yijianbaoshui-radio-icon J-yijianbaoshui-zero" id="cash"></div></div>
            </div>
          </div>
          <div class="classyijianbanshui-btn">
            <div id="oneKeyTaxReport" class="classyijianbanshui-btn-item">一键报税</div>
            <div id="taxCompletion" class="classyijianbanshui-btn-item-complete">申报完成</div>
          </div>
        </div>
      </div>
    `);

    $('body').append(btn);
    $('body').append(main);

    const yiJianBaoShuiBtn = $('#yiJianBaoShuiBtn');
    const yiJianBaoShuiPopup = $('#yiJianBaoShuiPopup');
    setTimeout(() => {
      yiJianBaoShuiBtn.addClass('yijianbaoshui-btn-show');
      yiJianBaoShuiBtn.find('span').addClass('yijiaobaoshui-btn-text-show');
    }, 10000);

    // 是否显示一键报税页面
    let isShowBtn = false;
    yiJianBaoShuiBtn.click(e => {
      if (isShowBtn) {
        yiJianBaoShuiPopup.removeClass('yijianbaoshui-active');
        yiJianBaoShuiBtn.addClass('yijianbaoshui-btn-show');
        yiJianBaoShuiBtn.find('span').addClass('yijiaobaoshui-btn-text-show');
        isShowBtn = !isShowBtn;
        return false;
      }
      yiJianBaoShuiPopup.addClass('yijianbaoshui-active');
      yiJianBaoShuiBtn.removeClass('yijianbaoshui-btn-show');
      yiJianBaoShuiBtn.find('span').removeClass('yijiaobaoshui-btn-text-show');
      isShowBtn = !isShowBtn;
    });

    // 重分类
    $('.J-yijianbaoshui-class').click(function (e) {
      let className = $(this).attr('class');
      if (className.includes('yijianbaoshui-radio-icon-select')) {
        $(this).removeClass('yijianbaoshui-radio-icon-select');
        return false;
      }
      $(this).addClass('yijianbaoshui-radio-icon-select');
    });
    // 零申报
    let zero = false;
    $('.J-yijianbaoshui-zero').click(function (e) {
      if (zero) {
        $(this).removeClass('yijianbaoshui-radio-icon-select');
        zero = !zero;
        return false;
      }
      $(this).addClass('yijianbaoshui-radio-icon-select');
      zero = !zero;
    });

    // 新版本提示
    chrome.runtime.sendMessage({
      event: 'getNewVersionInfo',
    })
    $('#yijianbaoshuiNewVersionNumber').click(e => {
      chrome.runtime.sendMessage({ event: 'jumpUpdate' });
    })

    $('#oneKeyTaxReport').click(() => {
      // 重构版本
      taxConfig = baseInfo.taxConfig[0];
      let ins, type;

      // 新版本
      let zero1 = zero;
      let isClassify1 = $('.J-yijianbaoshui-class').attr('class').includes('yijianbaoshui-radio-icon-select');
      console.log(isClassify1)
      if (taxConfig.isSupportTaxNationType) {
        ins = $('#taxRepotIns').val();
        type = 'balance'; // saas 会根据是否为财务报表和月季报所得税进行数据转化，此处应处理为其中之一
      } else {
        ins = $('#tax-type > select').find('option:selected')[0].dataset.ins || '';
        type = $('#tax-type > select').find('option:selected')[0].dataset.type;
        if (type === 'balance') {
          zero1 = false;
        } else if (type === 'cash') {
          zero1 = zero;
        } else {
          zero1 = false;
          isClassify1 = false;
        }
      }
      let startTime = $('#period-start').val();
      let endTime = $('#period-end').val();


      let postData = {
        type,
        ins,
        startTime,
        endTime,
        zero: zero1,
        isClassify: isClassify1
      };

      let { isSupportLastYears, isSupportLastYearsBefore } = isSupportCwbbYears(baseInfo.companyInfo, postData);
      if (!isSupportLastYears) {
        chrome.runtime.sendMessage({
          event: 'notifications',
          data: {
            message: `该账套的启用时间为${baseInfo.companyInfo.startDate}, 暂时无法获得去年的数据，请手工填写`
          }
        });
        return false;
      }
      if (['profit', 'cash'].includes(type) && !isSupportLastYearsBefore) {
        chrome.runtime.sendMessage({
          event: 'notifications',
          data: {
            message: `该账套的启用时间为${baseInfo.companyInfo.startDate}, 暂时无法获得前年的数据，只能填写去年数据，请手工填写前年数据`
          }
        });
      }

      chrome.runtime.sendMessage({
        event: 'fillTax',
        data: postData
      });
    });
    // 同步申报种类
    $('#syncDeclarationTypes').click(() => {
      window.postMessage(
        {
          event: 'syncReportInfo',
          sender: 'content-script'
        },
        '*'
      );
    });
    // 同步申报列表
    $('#syncDeclarationList').click(() => {
      window.postMessage(
        {
          event: 'syncReport',
          sender: 'content-script'
        },
        '*'
      );
    });
    // 申报完成
    $('#taxCompletion').click(() => {
      chrome.runtime.sendMessage({ event: 'declareTaxCompletion' })
    });
  }
})();
